// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package file

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"context"
	"database/sql"
	"errors"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileGetByNameLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileGetByNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileGetByNameLogic {
	return &FileGetByNameLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileGetByNameLogic) FileGetByName(req *types.FileByNameReq) (resp string, err error) {
	name := req.Name
	key := req.ApiKey
	if key == "" {
		return "", errors.New("apikey不能为空")
	}
	usersModel := model.NewUsersModel(l.svcCtx.Conn)
	user, err := usersModel.FindByApiKey(l.ctx, key)
	if err != nil || errors.Is(err, sql.ErrNoRows) {
		return "", errors.New("用户不存在")
	}
	userId := user.Id
	fileModel := model.NewSysFileModel(l.svcCtx.Conn)
	files, err := fileModel.FindByFileName(l.ctx, userId, name)
	if err != nil {
		return "", err
	}

	if len(files) > 0 {
		firstFile := files[0]
		return sqlutil.NullStringToString(firstFile.Src), nil
	}

	return "", nil
}
